package org.wyw.solution;

import org.wyw.entiry.ListNode;

/**
 * 链表反转
 */
@Solution(
        id = 1,
        title = "链表反转",
        difficulty = "medium",
        link = "https://leetcode.cn/problems/reverse-linked-list/submissions/596818475/"
)
public class Solution001 {

    // 迭代 逐个反转,记录当前节点的下一个节点后，反转当前节点，
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = null; //记录上一个节点,遍历链表结束时，该节点即为头节点
        while (head != null) {
            ListNode next = head.next; // 保存下个节点
            head.next = pre; //反转当前节点
            pre = head; //pre 后移一位到当前节点
            head = next; //当前节点后移
        }
        return pre;
    }
}
